package com.android.manghe.common;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import androidx.core.content.ContextCompat;
import androidx.multidex.MultiDex;

import com.android.base.tools.LogUtil;
import com.android.manghe.BuildConfig;
import com.android.manghe.R;
import com.android.manghe.cache.UserHolder;
import com.android.manghe.common.webview.ERefreshWebType;
import com.android.manghe.common.webview.WebViewActivity;
import com.android.manghe.common.webview.WebViewParameter;
import com.android.manghe.config.ConstantsUrl;
import com.android.manghe.detail.activity.GoodDetailActivity;
import com.android.manghe.main.MainActivity;
import com.android.manghe.user.activity.LoginActivity;
import com.android.manghe.utils.socket.AppResponseDispatcher;
import com.fm.openinstall.OpenInstall;
import com.hjq.bar.TitleBar;
import com.hjq.bar.style.TitleBarLightStyle;
import com.meiqia.core.callback.OnInitCallback;
import com.meiqia.meiqiasdk.util.MQConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.commonsdk.UMConfigure;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.MsgConstant;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengNotificationClickHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.UMShareConfig;
import com.zhangke.websocket.WebSocketSetting;

import org.android.agoo.huawei.HuaWeiRegister;
import org.android.agoo.mezu.MeizuRegister;
import org.android.agoo.oppo.OppoRegister;
import org.android.agoo.vivo.VivoRegister;
import org.android.agoo.xiaomi.MiPushRegistar;

public class MyApplication extends Application {


    @Override
    public void onCreate() {
        super.onCreate();
        initTitleBar();
        initWebSocket();
        LogUtil.init(true);
    }

    private void initTitleBar() {
        // 初始化标题栏全局样式
        TitleBar.initStyle(new TitleBarLightStyle(this) {

            @Override
            public Drawable getBackground() {
                return new ColorDrawable(ContextCompat.getColor(getApplicationContext(), R.color.white));
            }

            @Override
            public Drawable getBackIcon() {
                return getDrawable(R.mipmap.icon_back_black);
            }

            @Override
            public int getTitleColor() {
                return ContextCompat.getColor(getApplicationContext(), R.color.colorFont33);
            }
        });
    }

    private void initWebSocket() {
        WebSocketSetting.setConnectUrl(ConstantsUrl.sockecturl);
        WebSocketSetting.setResponseProcessDelivery(new AppResponseDispatcher());
        WebSocketSetting.setReconnectWithNetworkChanged(true);
    }


    public static void initUemng(Application context) {
        /* ---------------------Umeng----------------------- */
        //----初始化
        UMConfigure.init(context, "619c4d8ee0f9bb492b696f40", "Umeng",
                UMConfigure.DEVICE_TYPE_PHONE, "");
        UMConfigure.setLogEnabled(true);
        //----第三方登录、分享

        MobclickAgent.setPageCollectionMode(MobclickAgent.PageMode.AUTO);
        PlatformConfig.setWeixin(ConstantsUrl.Default_WX_APPID, ConstantsUrl.Default_WX_SERCET);
        PlatformConfig.setWXFileProvider("com.android.manghe.fileprovider");

        PlatformConfig.setQQZone(ConstantsUrl.QQ_APPID, ConstantsUrl.QQ_SECRET);
        PlatformConfig.setQQFileProvider("com.android.manghe.fileprovider");

        UMShareConfig config = new UMShareConfig();
        config.isNeedAuthOnGetUserInfo(true);
        UMShareAPI.get(context).setShareConfig(config);
        //----推送
        PushAgent mPushAgent = PushAgent.getInstance(context);
        PushAgent.getInstance(context).onAppStart();
        mPushAgent.setNotificationPlaySound(MsgConstant.NOTIFICATION_PLAY_SDK_ENABLE);
        /**
         * 自定义行为的回调处理，参考文档：高级功能-通知的展示及提醒-自定义通知打开动作
         * UmengNotificationClickHandler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * */
        UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {

            @Override
            public void launchApp(Context context, UMessage msg) {
                super.launchApp(context, msg);
                try {
                    if (msg.extra.containsKey("jumpType")) {
                        if (UserHolder.getUserInfo(context) == null) {
                            LoginActivity.Companion.showNewTaskActivity(context);
                        } else {
                            String jumpType = msg.extra.get("jumpType");
                            if (TextUtils.equals("URL", jumpType)) {
                                WebViewActivity.showNewTaskActivity(false,
                                        context, new WebViewParameter.WebParameterBuilder()
                                                .setUrl(msg.extra.get("urlStr"))
                                                .setShowProgress(true)
                                                .setCanHistoryGoBackOrForward(true)
                                                .setReloadable(true)
                                                .setReloadType(ERefreshWebType.ClickRefresh)
                                                .setCustomTitle(msg.extra.get("urlTitle"))
                                                .build());
                            } else if (TextUtils.equals("Auction", jumpType)) {
                                Intent intent = new Intent(context, GoodDetailActivity.class);
                                intent.putExtra("auctionId", msg.extra.get("auctionId"));
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            } else if (TextUtils.equals("MySetting", jumpType)) {
                                Intent intent = new Intent(context, MainActivity.class);
                                intent.putExtra("isToChangeTab", true);
                                intent.putExtra("position", 4);
                                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                context.startActivity(intent);
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void openUrl(Context context, UMessage msg) {
                super.openUrl(context, msg);
            }

            @Override
            public void openActivity(Context context, UMessage msg) {
                super.openActivity(context, msg);

            }

            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
                Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
            }
        };
        //使用自定义的NotificationHandler
        mPushAgent.setNotificationClickHandler(notificationClickHandler);
        //注册推送服务，每次调用register方法都会回调该接口
        mPushAgent.register(new IUmengRegisterCallback() {
            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回deviceToken deviceToken是推送消息的唯一标志
                Log.i("Umeng_Push", "注册成功：deviceToken：-------->  " + deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("Umeng_Push", "注册失败：-------->  " + "s:" + s + ",s1:" + s1);
            }
        });

        //厂商通道-小米
        MiPushRegistar.register(context, "2882303761518039587", "5101803932587");//AppId, AppKey
        //厂商通道-华为
        HuaWeiRegister.register(context);
        //厂商通道-魅族
        MeizuRegister.register(context, "", "");
        //厂商通道-Oppo
        OppoRegister.register(context, "30115297", "0cf1f7f372454e18a88eb0e1d91e0047");
        //厂商通道-Vivo
        VivoRegister.register(context);
    }

    //美洽客服系统：
    public static void initMeiQia(Application application) {
        MQConfig.init(application, "6cfe88e81434fe795985cbfb53a06710", new OnInitCallback() {
            @Override
            public void onSuccess(String clientId) {

            }

            @Override
            public void onFailure(int code, String message) {

            }
        });
    }

    public static void initOpenInstall(ApplicationInfo applicationInfo, Application application) {
        if (isMainProcess(applicationInfo, application)) {
            OpenInstall.init(application);
        }
    }

    private static boolean isMainProcess(ApplicationInfo applicationInfo, Application application) {
        int pid = android.os.Process.myPid();
        ActivityManager activityManager = (ActivityManager) application.getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo appProcess : activityManager.getRunningAppProcesses()) {
            if (appProcess.pid == pid) {
                return applicationInfo.packageName.equals(appProcess.processName);
            }
        }
        return false;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}
